package org.extframework.ld.service.pojo;

import java.util.Random;

import org.extframework.ld.bean.SerialNumber;
import org.extframework.ld.bean.model.UpdateInfo;
import org.extframework.ld.http.global.ExtSystemGlobal;
import org.extframework.ld.service.SerialNumberManager;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author : Dong.Li
 * @created : 2013-1-23
 * @version : 1.0
 * @description :
 */
public class DefaultSerialNumber extends DefaultBaseManager
	implements SerialNumberManager{

	private Random random = new Random();
	
	@Transactional
	public void create(SerialNumber number) {
		number.setUpdateInfo(new UpdateInfo(ExtSystemGlobal.getUserSession()));
		commDao.store(number);
	}

	@Transactional
	public int get(String unqie) {
		Object object = commDao.findByQueryUniqueResult("FROM SerialNumber number WHERE number.unqie=:unqie", "unqie", unqie);
		SerialNumber number = (SerialNumber) object;
		return number.getUumber();
	}

	@Transactional
	public boolean isHashNumber(String unique) {
		Object object = commDao.findByQueryUniqueResult("FROM SerialNumber number WHERE number.unqie=:unqie", "unqie", unique);
		return object!=null;
	}

	@Transactional
	public String getCode(String serialNumberUnqie) {
		if(isHashNumber(serialNumberUnqie)){
			return serialNumberUnqie+"_"+(Math.abs(random.nextInt(1000))+1000)+get(serialNumberUnqie);
		}else{
			SerialNumber number = new SerialNumber();
			number.setUnqie(serialNumberUnqie);
			number.setRemark(serialNumberUnqie+"流水号");
			number.setAddVar(1);
			number.setUumber(0);
			create(number);
		}
		return getCode(serialNumberUnqie);
	}

}
